package com.uxwine.alarm;


import java.util.Calendar;

import com.uxwine.util.Log;

import android.content.Context;
import android.database.Cursor;
import android.text.format.DateFormat;

class AlarmMgr
{
	Context mCtx;
	Snooze mSnooze;
//	AlertMgr mAlert;
	static AlarmMgr mInstance;
	public static synchronized AlarmMgr getInstance(Context ctx)
	{
		if(null == mInstance)
			mInstance = new AlarmMgr(ctx.getApplicationContext());
		return mInstance;
	}
	private AlarmMgr(Context ctx)
	{ 
		mCtx = ctx;
		mSnooze = Snooze.getInstance(ctx);
	}
	
	public Alarm nextAlarm()
	{
		Alarm snooze = mSnooze.getEnableAlarm();
		Alarm alarm = nextAlarm(mCtx);
		if(null != snooze)
		{
			final Calendar c = Calendar.getInstance();
			long now = c.getTimeInMillis();
			c.setTimeInMillis(snooze.trigger);
			Log.f("snooze", "nextAlarm : snooze->" + new DateFormat().format("yyyy/MM/dd kk:mm", c));
			if(snooze.trigger < now + 100)
			{
				Log.f("snooze", "nextAlarm : snooze is earlier than now");
				return alarm;
			}
			
			if(alarm == null)
			{
				Log.f("snooze", "nextAlarm : alarm==null");	
				return snooze;
			}
			
			if(snooze.trigger < alarm.trigger)
			{
				c.setTimeInMillis(alarm.trigger);
				Log.f("snooze", "nextAlarm : alarm->" + new DateFormat().format("yyyy/MM/dd kk:mm", c));	
				return snooze;			
			}
			Log.f("snooze", "nextAlarm : snooze is later than alarm");
			AlertMgr.getInstance(mCtx).showTimeout(snooze);	
			mSnooze.clear();
		}
		Log.f("snooze", "nextAlarm : snooze is later than alarm");
		return alarm;
	}	
	
	public boolean snoozeAlarm(Alarm alarm)
	{
		if(null == alarm)
			throw new NullPointerException();
		mSnooze.saveSnoozeAlarm(alarm);
		return !mSnooze.isTimeout();
	}
	
	public void clearSnooze()
	{
		mSnooze.clear();
	}
	
	public void resetSnoozedAlarm(int id)
	{
		mSnooze.resetSnoozedAlarm(id);
	}
	
	public Alarm getEnableSnooze()
	{
		return mSnooze.getEnableAlarm();
	}
	
	public boolean isSnoozed(int id)
	{
		return mSnooze.isSnoozed(id);
	}
	
	public boolean canSnoozed(int id)
	{
		return mSnooze.canSnoozed(id);
	}
	
	/**
	 * 从数据库中找到最近的Alarm
	 */
	private Alarm nextAlarm(Context ctx)
	{
		Alarm alarm = null;
		long minTime = Long.MAX_VALUE;
		long now = System.currentTimeMillis();
		Cursor cursor = AlarmDao.getEnabledAlarm(ctx.getContentResolver());
		
		if (cursor == null) 
			return alarm;
		
		while (cursor.moveToNext())
		{
		    Alarm a = new Alarm(cursor);
		    // A time of 0 indicates this is a repeating alarm, so
		    // calculate the time to get the next alert.
		    if (a.trigger == 0) 
		    {
		        a.trigger = AlarmCalc.triggerTime(a);
		    } 
		    else if (a.trigger < now)
		    {
		        // Expired alarm, disable it and move along.
		        AlarmDao.enableAlarm(ctx, a, false);
		        continue;
		    }
		    if (a.trigger < minTime)
		    {
		        minTime = a.trigger;
		        alarm = a;
		    }
		}
		if(alarm != null)
			alarm.type = Alarm.ALARM_OR;
		cursor.close();
		return alarm;
	}
}
